import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import teacherTable from "./teacherSearch";
import { PageVo, Teacher, TeacherQueryVo } from "@api/model";
import { remove, getById, update, save, uploadFile } from "@api/teacher";

// 讲师表单的数据类型
interface TeacherForm {
    name: string;
    level: number;
    career: string;
    intro?: string;
    avatar?: string;
    sort?: number;
}

// 讲师表单的响应式数据
const teacherFormReactive = reactive<{ teacherForm: TeacherForm }>({
    /*
       为了给reactive对象赋值，需要将对象定义为其中的一个属性。
      */
    teacherForm: {
        name: "",
        level: 1,
        career: "",
        intro: "",
        avatar: "",
        sort: 0,
    },
});

export default function teacherForm() {
    // 获取讲师列表数据
    const { getTeacherDataList } = teacherTable();
    // 对话框默认不可见
    const visible = ref(false);
    // 是否编辑用户
    const isEdit = ref(false);
    // 重置表单
    function resetTeacherForm() {
        teacherFormReactive.teacherForm = {
            name: "",
            level: 1,
            career: "",
            intro: "",
            avatar: "",
            sort: 0,
        };
    }
    function addTeacher() {
        // 设置当前不是编辑模式：true代表添加  false代表更新
        isEdit.value = false
        // 开启输入框
        visible.value = true
    }

    // 更新教师信息的函数
    // 修改讲师
    function editTeacher(id: string) {
        getById(id).then((teacher: any) => {
            // 将请求响应的数据赋值给绑定了表单的响应式对象
            teacherFormReactive.teacherForm = teacher.data;
            // 设置弹窗为编辑模式
            isEdit.value = true;
            // 显示弹窗
            visible.value = true;
        });
    }

    // 删除完成后，马上更新列表界面
    async function delTeacher(id: string) {
        await ElMessageBox.confirm("确定要删除当前讲师？", "提示", {
            type: "warning",
        }).then(() => {
            remove(id).then(() => {
                ElMessage.success("删除成功");
                getTeacherDataList();
            });
        }).catch(() => { });

    }
    // 讲师表单的校验数据
    const rules = reactive({
        name: [
            { required: true, message: "请填写姓名", trigger: "blur" },
            { min: 2, max: 20, message: "用户名必须在2-20位字符", trigger: "blur" },
        ],
        level: [{ required: true, message: "请选择讲师头衔", trigger: "blur" }],
        career: [{ required: true, message: "请填写讲师资历", trigger: "blur" }],
        intro: [{ required: true, message: "请填写讲师简介", trigger: "blur" }],
    });

    /*
     提交表单
     1. 校验表单
     2. 判断提交类型
     3. 新增或修改
     */
    // 获取当前组件实例对象
    const currentInstance = getCurrentInstance();
    function submit(event: MouseEvent) {

        (currentInstance?.refs.teacherFormRef as any).validate((valid: boolean) => {
            if (!valid) {
                return;
            }
            // 只有校验成功才会执行提交操作
            // 判断是编辑还是保存
            if (isEdit.value) {
                // 更新数据
                update(teacherFormReactive.teacherForm as Teacher)
                    .then((resp: any) => {
                        ElMessage.success(resp);
                        visible.value = false;
                        // 更新视图
                        getTeacherDataList();
                    })

            } else {
                // 添加数据
                save(teacherFormReactive.teacherForm as Teacher)
                    .then((resp: any) => {
                        ElMessage.success(resp);
                        visible.value = false;
                        // 更新视图
                        getTeacherDataList();
                    })
            }
        });
    }
    // 文件上传
    function cutDown(cutImage: { file: File }) {
        // 从解构的对象中获取文件传给上传api
        uploadFile([cutImage.file]).then(avatar => {
            // 成功回调就是图片的地址
            // 将地址保存的表单数据对象中，在表单提交数据时就已经有图片地址了
            teacherFormReactive.teacherForm.avatar = avatar
            ElMessage.success("头像上传成功")
        })
    }

    return {
        visible,
        resetTeacherForm,
        ...toRefs(teacherFormReactive),
        addTeacher,
        editTeacher,
        delTeacher,
        submit,
        rules,
        cutDown
    };
}